<?php


namespace app\admin\system\controller;


use app\admin\system\logic\RoleLogic;
use app\common\controller\BaseAdminController;
use app\model\SysRole;
use app\model\SysRoleMenu;
use think\facade\Db;

class RoleController extends BaseAdminController
{
    protected $noNeedRight = [
        'listNormalRole',
        'listRoleElSelect',
    ];

    protected function init()
    {
        parent::init();
        $this->logic = new RoleLogic();
    }

    protected function searchWhere()
    {
        $where = [
            ['status', '<>', -1]
        ];
        $this->form['keyword'] && $where[] = ['name|alias', 'like', "%{$this->form['keyword']}%"];
        $this->form['status'] && $where[] = ['status', '=', $this->form['status']];
        return $where;
    }

    public function getAll()
    {
        $data = $this->logic->getList([
            'status' => 1
        ]);
        return $this->success($data);
    }

    public function allocation()
    {
        $menu_ids = input('menu_ids');
        $dept_ids = input('dept_ids');
        $data_type = input('data_type'); //数据类型
        $role_id = input('id');
        $inst = [];
        foreach ($menu_ids as $id) {
            $inst[] = [
                'role_id' => $role_id,
                'menu_id' => $id,
            ];
        }
        Db::transaction(function () use ($dept_ids, $data_type, $role_id, $inst) {
            SysRoleMenu::where('role_id', '=', $role_id)->delete();
            SysRoleMenu::insertAll($inst);
            SysRole::where('id', '=', $role_id)->update([
                'data_type' => $data_type,
                'dept_ids' => implode(',',$dept_ids)
            ]);

        });
        return $this->success();
    }

    public function roleAssigned()
    {
        $role_id = input('id');

        $menu_ids = SysRoleMenu::where('role_id', '=', $role_id)->column('menu_id');

        $role = SysRole::where('id', '=', $role_id)->field([
            'data_type',
            'dept_ids',
        ])->find();

        return $this->success([
            'menu_ids' => $menu_ids,
            'dept_ids' =>strToArr($role['dept_ids']),
            'data_type' => $role['data_type']."",
        ]);
    }

    public function remove()
    {
        $ids = request()->input('ids', [request()->input($this->idKey)]);
        if (!empty($ids)) {
            $this->logic->where([
                ['id', 'in', $ids]
            ])->update([
                'status'=>-1
            ]);
            return $this->success();
        } else {
            return $this->error('参数错误，请检查');
        }
    }
}